package cn.changeforyou.web.dao.mybatis.ext;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

public class OneToManyStringListTypeHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {

    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String dataStr = rs.getString(columnName);
        return getList(dataStr);
    }

    private List<String> getList(String dataStr) {
        String[] split = dataStr.split(",");
        return Arrays.asList(split);
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String dataStr = rs.getString(columnIndex);
        return getList(dataStr);
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String dataStr = cs.getString(columnIndex);
        return getList(dataStr);
    }
}
